import { app, shell, BrowserWindow, dialog, screen, ipcMain, session } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

import TrayService from './appTray/index'
import './icpMainComm/index'

import { updateHandle } from './autoUpdater/index'

let mainWindow

function createWindow() {
  // Create the browser window.
  const size = screen?.getPrimaryDisplay()?.workAreaSize || {
    width: 900,
    height: 670
  }
  console.log(size)
  let width = parseInt(size.width * 0.82, 10)
  const height = parseInt(size.height * 0.82, 10)
  // eslint-disable-next-line radix
  const minWIdth = parseInt(size.width * 0.5)
  const minHeight = parseInt(size.height * 0.55, 10)
  if (width % 2 !== 0) {
    width += 1 // 宽度为偶数
  }
  let _titleBarStyle = 'default'
  if (process.platform === 'darwin') {
    _titleBarStyle = 'hiddenInset'
  } else if (process.platform === 'win32') {
    _titleBarStyle = 'hidden'
  }
  mainWindow = new BrowserWindow({
    height,
    width,
    minHeight: minHeight,
    minWidth: minWIdth,
    show: false,
    frame: false,
    transparent: false,
    backgroundColor: 'transparent',
    autoHideMenuBar: true,
    titleBarStyle: _titleBarStyle,
    ...(process.platform === 'linux' ? { icon } : { icon }),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      webSecurity: false,
      webviewTag: false,
      contextIsolation: false
    },
    alwaysOnTop: false
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  mainWindow.on('close', (event) => {
    if (
      dialog.showMessageBoxSync(mainWindow, {
        type: 'info',
        buttons: ['最小化到托盘', '直接退出'],
        title: '提示',
        message: '确定要退出吗？',
        defaultId: 0,
        cancelId: 1
      }) === 0
    ) {
      event.preventDefault()
      mainWindow.hide()
    } else {
      app.exit()
    }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'], {})
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'), {})
  }
  // F12打开调试模式
  // mainWindow.webContents.openDevTools()
  // 创建系统托盘
  new TrayService(mainWindow)

  // 当窗口进入焦点时会调用它, 但您可能会使用超时或其他一些事件来禁用它。
  mainWindow.once('focus', () => mainWindow.flashFrame(false))
  mainWindow.flashFrame(true)

  // 禁用右键菜单
  preventDragbarContext(mainWindow)

  // 更新模块
  updateHandle(mainWindow)

  /**
   * @请求拦截修改头部
   */
  session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    let origin = new URL(details.url).origin
    details.requestHeaders['User-Agent'] = 'okhttp/3.10.0.2'
    details.requestHeaders['origin'] = origin
    details.requestHeaders['referer'] = origin
    callback({ cancel: false, requestHeaders: details.requestHeaders })
  })

  // mainWindow.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
  //   callback({ requestHeaders: { Origin: '*', ...details.requestHeaders } })
  // })
  // mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
  //   callback({
  //     responseHeaders: {
  //       'Access-Control-Allow-Origin': ['*'],
  //       ...details.responseHeaders
  //     }
  //   })
  // })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  // await netLog.startLogging('net-log.log')
  // // After some network events
  // const path = await netLog.stopLogging()
  // console.log('Net-logs written to', path)
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    // 关闭程序
    app.quit()
    //关闭最小化
    // app.exit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

// 最小化窗口
ipcMain.on('window-min', () => {
  mainWindow.minimize()
})
// 最大化窗口
ipcMain.on('window-max', (event, arg) => {
  // 如果已经是最大化窗口就还原
  console.log(`window-max:我接收到了同步消息`, arg)
  let isMaximized = mainWindow.isMaximized()
  if (isMaximized) {
    mainWindow.restore()
  } else {
    mainWindow.maximize()
  }
  // event.returnValue = isMaximized
  event.sender.send('window-max', isMaximized) // 返回一个'pong'
})
// 关闭窗口
ipcMain.on('window-close', () => {
  mainWindow.close()
})

//置顶
ipcMain.on('window-top', (event, arg) => {
  console.log(`window-max:我接收到了同步消息`, arg)
  let isAlwaysOnTop = mainWindow.isAlwaysOnTop()
  if (isAlwaysOnTop) {
    mainWindow.setAlwaysOnTop(false)
    BrowserWindow.getFocusedWindow().webContents.send('alwaysOnTop', 'no')
  } else {
    mainWindow.setAlwaysOnTop(true)
    BrowserWindow.getFocusedWindow().webContents.send('alwaysOnTop', 'yes')
  }
  // event.returnValue = isAlwaysOnTop
  event.sender.send('window-top', isAlwaysOnTop) // 返回一个'pong'
})

// 禁用右键菜单
function preventDragbarContext(win) {
  var WM_INITMENU = 0x116 //278
  win.hookWindowMessage(WM_INITMENU, function () {
    win.setEnabled(false)
    setTimeout(() => {
      win.setEnabled(true)
    }, 100)
    return true
  })
}
